package robot;
import lejos.nxt.LCD;
import lejos.nxt.Sound;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class Connection 
{

	private static final int WEAK_SIGNAL_LIMIT = 10;



	private static final int WEAK_BLUETOOTH = 888888;



	int timeOut;
	CommandQueue theQueue;
	Parser parser;
	//strings describing the state of the connection
	String connected = "Connected";
	String waiting = "Waiting...";
	String closing = "Closing...";
	//IO streams for the btc
	DataInputStream dis = null;
	DataOutputStream dos = null;
	//Connection to form with the device
	BTConnection btc = null;

	public boolean sendIntToBase(int output) //send to control station/base
	{
 		boolean success = true;
 
		try {			
			//writeInt , not write
			dos.writeInt(output);
 		} catch (IOException e) {
 			e.printStackTrace();
 			success= false;
		}
		
		try {
			dos.flush();
		} catch (IOException e) {
			e.printStackTrace();
			success= false;
		}
		
		return success;
	}
	
	public boolean sendStrToBase(String output) //send to control station/base
	{
		boolean success = false;
		return success;
	}
	
	public void receive ()
	{

	}
	
	//first call this method ! 
	public void connect()
	{
		//inform the user that it's waiting for a connection
		LCD.drawString("waiting",0,0);
		LCD.refresh();

		//two beeps indicate it's initialized and waiting for a connection
		Sound.twoBeeps();

		//this blocks until a bluetooth connection is made
		btc = Bluetooth.waitForConnection();

		//once the connection is made, initialize the IO streams
		dis = btc.openDataInputStream();
		dos = btc.openDataOutputStream();

		//play something to signify that a connection has been made;
		//program is no longer blocked
		Sound.beepSequenceUp();

		LCD.drawString("connected",0,0);
		LCD.refresh();
	}

	public int getNextCommand() throws InterruptedException
	{
		int n = -1;

		try {
			n = dis.readInt();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return n;
	}

	public boolean hasWeakConnection(){
		if (btc.getSignalStrength()<= WEAK_SIGNAL_LIMIT)
		{
			sendIntToBase(WEAK_BLUETOOTH); //means bluetooth connection weak;
			return true;
		}
		return false;
	}

	public void shutdown() throws InterruptedException{
		//program's over, shut everything off..
		try{
		dis.close();
		dos.close();
		Thread.sleep(100); // wait for data to drain
		}
		catch (IOException e) {
 			e.printStackTrace();
		}
		LCD.clear();
		LCD.drawString(closing,0,0);
		LCD.refresh();
		btc.close();
		LCD.clear();
	}
	
	public void sendConfirmation()
	{
		int output = 0; //determined by protocol
		sendIntToBase(output);		
	}
	
	public void sendSensorData(int sensorOutput)
	{
		sendIntToBase(sensorOutput);
	}
	
}
